package com.lixh.sdk.base.util

import android.content.Context
import android.content.Intent
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.net.wifi.WifiInfo
import android.net.wifi.WifiManager
import android.os.Build
import android.provider.Settings
import java.net.InetAddress
import java.net.UnknownHostException


fun wifiManager(): WifiManager? {
    return applicationContext.getSystemService(Context.WIFI_SERVICE)
            as? WifiManager ?: return null
}


fun connectivityManager(): ConnectivityManager? {
    return applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE)
            as? ConnectivityManager ?: return null
}

fun wifiConnectionInfo(): WifiInfo? {
    return wifiManager()?.connectionInfo
}

fun isWifiEnabled(): Boolean {
    return wifiManager()?.isWifiEnabled ?: false
}

fun isAvailableByDns(): Boolean {
    return isAvailableByDns("")
}

fun isAvailableByDns(str: String = "www.baidu.com"): Boolean {
    return try {
        InetAddress.getByName(str) != null
    } catch (e: UnknownHostException) {
        e.printStackTrace()
        false
    }
}

fun turnOnWifi() {
    if (!isWifiEnabled()) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            val settingsIntent = Intent(Settings.Panel.ACTION_WIFI)
            settingsIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            application.startActivity(settingsIntent)
        } else {
            wifiManager()?.let {
                @Suppress("DEPRECATION")
                it.isWifiEnabled = true
            }
        }
    }
}

fun turnOffWifi() {
    if (isWifiEnabled()) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            val settingsIntent = Intent(Settings.Panel.ACTION_WIFI)
            settingsIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            application.startActivity(settingsIntent)
        } else {
            wifiManager()?.let {
                @Suppress("DEPRECATION")
                it.isWifiEnabled = false
            }
        }
    }
}

fun isConnectedToWifi(): Boolean {
    return connectivityManager()?.let {
        val network = it.activeNetwork ?: return false
        val activeNetwork = it.getNetworkCapabilities(network) ?: return false
        return when {
            activeNetwork.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true
            else -> false
        }
    } ?: false
}